/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import commonEvent from '@ohos.commonEventManager';
import Prompt from '@system.prompt';
import Logger from '../log/Logger';
import { AdStatus } from './AdStatus';

const KEY_REWARD_DATA = "reward_ad_data";
const KEY_REWARD_STATUS = "reward_ad_status";
const TAG = 'Ads Demo-FullScreenAdStatusHandler';

export class FullScreenAdStatusHandler {
  // 用于保存创建成功的订阅者对象，后续使用其完成订阅及退订的动作
  private subscriber;

  // 该方法需要在广告展示前调用
  public registerPPSReceiver(): void {
    if (this.subscriber) {
      this.unRegisterPPSReceiver();
    }
    // 订阅者信息
    const subscribeInfo = {
      events: ["com.company.pps.action.PPS_REWARD_STATUS_CHANGED"],
    };
    // 创建订阅者回调
    commonEvent.createSubscriber(subscribeInfo, (err, commonEventSubscriber) => {
      if (err) {
        Logger.info(TAG, `createSubscriber error, ${JSON.stringify(err)}`);
        return;
      }
      Logger.info(TAG, `createSubscriber success`);
      this.subscriber = commonEventSubscriber;
      // 订阅公共事件回调
      if (!this.subscriber) {
        Logger.info(TAG, `need create subscriber`);
        return;
      }
      commonEvent.subscribe(this.subscriber, (err, commonEventData) => {
        if (err) {
          Logger.error(TAG, `subscribe error, ${JSON.stringify(err)}`);
        } else {
          Logger.info(TAG, `subscribe data, ${JSON.stringify(commonEventData)}`);
          const status: string = commonEventData.parameters[KEY_REWARD_STATUS];
          switch (status) {
            case AdStatus.AD_OPEN:
              Logger.info(TAG, `onAdOpen`);
              Prompt.showToast({
                message: 'full screen ad open',
                duration: 1000
              });
              break;
            case AdStatus.AD_CLICKED:
              Logger.info(TAG, `onAdClick`);
              Prompt.showToast({
                message: 'full screen ad click',
                duration: 1000
              });
              break;
            case AdStatus.AD_CLOSED:
              Logger.info(TAG, `onAdClose`);
              Prompt.showToast({
                message: 'full screen ad close',
                duration: 1000
              });
              this.unRegisterPPSReceiver();
              break;
            case AdStatus.AD_REWARDED:
              const rewardData = commonEventData.parameters[KEY_REWARD_DATA];
              const rewardType = rewardData?.rewardType;
              const rewardAmount = rewardData?.rewardAmount;
              Logger.info(TAG, `onAdReward, rewardType: ${rewardType}, rewardAmount: ${rewardAmount}`);
              Prompt.showToast({
                message: `full screen ad reward, rewardType: ${rewardType}, rewardAmount: ${rewardAmount}`,
                duration: 1000
              });
              break;
            case AdStatus.AD_VIDEO_START:
              Logger.info(TAG, `onAdVideoStart`);
              Prompt.showToast({
                message: 'full screen ad video start',
                duration: 1000
              });
              break;
            case AdStatus.AD_COMPLETED:
              Logger.info(TAG, `onAdCompleted`);
              Prompt.showToast({
                message: 'full screen ad completed',
                duration: 1000
              });
              break;
            default:
              break;
          }
        }
      });
    });
  }

  public unRegisterPPSReceiver(): void {
    commonEvent.unsubscribe(this.subscriber, (err) => {
      if (err) {
        Logger.error(TAG, `unsubscribe error, ${JSON.stringify(err)}`);
      } else {
        Logger.info(TAG, `unsubscribe success`);
        this.subscriber = null;
      }
    });
  }
}